package io.bloom.web.service;

import io.bloom.search.IndexTemplate;
import io.bloom.search.SearchHelper;
import io.bloom.search.Searchable;
import io.bloom.web.model.LinkDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.search.Query;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SearchService implements InitializingBean {


    private IndexTemplate template;

    public List<Searchable> search(String keyword) throws IOException {
        log.info("search keyword:{}", keyword);

        Query query = SearchHelper.makeQuery("title", keyword, 10.f);

        return template.find(LinkDO.class, query, null, null);
    }

    public void index(Searchable searchable) throws IOException {
        List<Searchable> list = new ArrayList<>();
        list.add(searchable);
        template.create(list, searchable.getClass());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String indexFolder = SearchService.class.getClassLoader().getResource("./").getFile() + "index";

        FileUtils.deleteDirectory(new File(indexFolder));
        FileUtils.forceMkdir(new File(indexFolder));
        template = IndexTemplate.init(indexFolder);
        log.info("index store at:{}", indexFolder);
    }
}
